<?php
declare(strict_types=1);

namespace App\Service\Admin;

use App\Enum\Code;
use App\Exception\BusinessException;
use App\Model\User;
use App\Repository\Admin\UserRepository;
use Hyperf\Di\Annotation\Inject;
use HyperfExt\Jwt\Contracts\JwtFactoryInterface;

class UserService
{
    #[Inject]
    private JwtFactoryInterface $jwtFactory;

    #[Inject]
    private UserRepository $userRepository;

    public function login(array $data)
    {
        $user = $this->userRepository->findAdminByName($data['name']);

        if ($user === null) {
            throw new BusinessException(Code::RequestParamError, '用户名不存在');
        }

        if (!password_verify($data['password'], $user->password)) {
            throw new BusinessException(Code::RequestParamError, '密码错误');
        }

        return $this->generateToken($user);
    }

    public function getUsers(array $params)
    {
        $page = $params['page'] ?? 1;
        $perPage = $params['perPage'] ?? 15;

        unset($params['page']);
        unset($params['perPage']);

        return $this->userRepository->getPaginatedUsers($params, $page, $perPage);
    }

    public function getUserDetail(int $id)
    {
        $user = $this->userRepository->getUserDetail($id);
        if ($user === null) {
            throw new BusinessException(Code::RequestParamError, '用户不存在');
        }

        return $user;
    }

    private function generateToken(User $user): string
    {
        $jwt = $this->jwtFactory->make();
        return $jwt->fromSubject($user);
    }

    public function updateRole(int $id, string $role)
    {
        $user = $this->userRepository->getUser($id);
        $user->role = $role;
        $this->userRepository->updateByModel($user);

        return $user;
    }

    public function updateStatus(int $id, string $status)
    {
        $user = $this->userRepository->getUser($id);
        $user->status = $status;
        $this->userRepository->updateByModel($user);

        return $user;
    }
}